const toString = Object.prototype.toString

/**
 * 描述 是否日期类型
 * @date 2020-04-25
 * @param {any} val
 * @returns {boolean}
 */
export function isDate(val: any): val is Date {
  return toString.call(val) === '[object Date]'
}

/**
 * 描述 是否对象类型
 * @param {any} val
 * @returns {boolean}
 */
// export function isObject(val: any): val is Object {
//   return val !== null && typeof val === 'object'
// }

/**
 * 描述 是否普通对象类型
 * @date 2020-04-25
 * @param {any} val
 * @returns {boolean}
 */
export function isPlainObject(val: any): val is Object {
  return toString.call(val) === '[object Object]'
}

/**
 * 描述 to对象继承from对象的属性,
 * @param {<F>} from
 * @param {<T>} to
 * @returns {F & T}
 */
export function extend<F, T>(from: F, to: T): F & T {
  for (const key in from) {
    ;(to as F & T)[key] = from[key] as any
  }
  return to as F & T
}

// 对象复制（失败操作）
export function clone<F, T>(from: F, to: T): F & T {
  return Object.assign(to, from)
}

/**
 * 描述 简易版深拷贝, 使用递归
 * @param {any[]} ...objs:any[]
 * @returns {any}
 */
export function deepMerge(...objs: any[]): any {
  let result = Object.create(null)
  objs.forEach((obj) => {
    if (obj) {
      Object.keys(obj).forEach((key) => {
        const val = obj[key]
        if (isPlainObject(val)) {
          if (isPlainObject(result[key])) {
            result[key] = deepMerge(result[key], val)
          } else {
            result[key] = deepMerge(val)
          }
        } else {
          result[key] = val
        }
      })
    }
  })
  return result
}

/**
 * 描述 判断val是否是FromData类型实例
 * @param {any} val
 * @returns {boolean}
 */
export function isFormData(val: any): val is FormData {
  return typeof val !== 'undefined' && val instanceof FormData
}

/**
 * 描述 判断val是否是URLSearchParams类型实例
 * @param {any} val
 * @returns {boolean}
 */
export function isURLSearchParams(val: any): val is URLSearchParams {
  return typeof val !== 'undefined' && val instanceof URLSearchParams
}

/**
 * 描述 判断url是否是绝对url地址
 * @param {any} url:string
 * @returns {any}
 */
export function isAbsoluteURL(url: string): boolean {
  return /(^[a-z][a-z\d\+\.\-]*:)?\/\//i.test(url)
}

/**
 * 描述 将baseURL和relativeURL合并
 * @param {string} baseURL:
 * @param {string?} relativeURL
 * @returns {any}
 */
export function combineURL(baseURL: string, relativeURL?: string): string {
  return relativeURL ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL
}
